package com.example.matchandroiddevices.scanlable;

import android.app.Activity;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.matchandroiddevices.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

public class ScanMode extends Activity implements OnClickListener, OnItemClickListener{
	
	private String mode;
	private Map<String,Integer> data;
	public static Integer soundid=null;
	public static SoundPool soundPool=null;
	Button btStart;
	Button btStop;
	Button btClear;
	ListView listView;
	ListView listinfo;
	TextView txNum;
	TextView txTime;
	TextView txCount;
	TextView txinfo;
	private Timer timer;
	private Handler mHandler;
	private boolean isCanceled = true;
	
	private static final int SCAN_INTERVAL = 10;
	private static final int MSG_UPDATE_LISTVIEW = 0;
	private static final int MSG_UPDATE_INFO=1;
	private static final int MSG_UPDATE_ANTNUM=2;
	private static boolean Scanflag=false;
	
	public volatile static ArrayList<HashMap<String, String>> mCurIvtClist;
	public volatile static ArrayList<HashMap<String, String>> mlastIvtClist;
	public volatile static ArrayList<HashMap<String, String>> mnewIvtClist;
	public volatile static ArrayList<HashMap<String, String>> mIvtInfolist;
	SimpleAdapter adapterTaglist;
	SimpleAdapter adapterInforlist;
	
	Thread mThread;
	volatile boolean mWorking=false;
	volatile boolean isfinish=false;
	long Count=0;
	long Number=0;
	long ScanTime =0;
	TextView antNumber;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try
		{
			setContentView(R.layout.query);
			mCurIvtClist = new ArrayList<HashMap<String, String>>();
			mlastIvtClist = new ArrayList<HashMap<String, String>>();
			mIvtInfolist = new ArrayList<HashMap<String, String>>();
			mnewIvtClist = new ArrayList<HashMap<String, String>>();
			adapterTaglist = new SimpleAdapter(ScanMode.this, mCurIvtClist, R.layout.listtag_items,
					new String[] { "tagUid","tagAnt"},
					new int[] { R.id.tv_Uid,R.id.tv_Ant});
			
			adapterInforlist = new SimpleAdapter(ScanMode.this, mIvtInfolist, R.layout.listinfo_items,
					new String[] {"tagInfo"},
					new int[] { R.id.Infotext});
			
			txNum = (TextView)findViewById(R.id.textNumber);
			txTime = (TextView)findViewById(R.id.textTime);
			txCount = (TextView)findViewById(R.id.textCount);
			antNumber = (TextView)findViewById(R.id.antNumber);
			
			btStart = (Button)findViewById(R.id.btn_startInventory);
			btStart.setOnClickListener(this);
			
			btStop = (Button)findViewById(R.id.btn_stopInventory);
			btStop.setOnClickListener(this);
			
			btClear = (Button)findViewById(R.id.btn_clearList);
			btClear.setOnClickListener(this);
			
			listinfo = (ListView)findViewById(R.id.list_inventoryInfo);
			
			listView = (ListView)findViewById(R.id.list_inventory_record);
			
			
			mHandler = new Handler(){

				@Override
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					switch (msg.what) {
					case MSG_UPDATE_LISTVIEW:
						try{
							mCurIvtClist.clear();
	            			if(mnewIvtClist.size()>0)
	            			{
	            				 for (int i = 0; i < mnewIvtClist.size(); i++) {
	            			            HashMap<String, String> temp = new HashMap<String, String>();
	            			            temp = mnewIvtClist.get(i);
	            			            mCurIvtClist.add(temp);
	            			        }
	            			}
	            			Number = mCurIvtClist.size();
							listView.setAdapter(adapterTaglist);
							adapterTaglist.notifyDataSetChanged();
							txCount.setText(String.valueOf(Count));
							txNum.setText(String.valueOf(Number));
							txTime.setText(String.valueOf(ScanTime));
							isfinish =true;
						}catch(Exception ex)
						{
							Log.d("MSG_UPDATE_LISTVIEW", ex.toString());
						}
						break;
					case MSG_UPDATE_INFO:
						 HashMap<String, String> temp = new HashMap<String, String>();
							temp.put("tagInfo", (String)msg.obj);
							if(mIvtInfolist.size()==0)
								mIvtInfolist.add(temp);
							else
								mIvtInfolist.add(0,temp);
						listinfo.setAdapter(adapterInforlist);
						adapterInforlist.notifyDataSetChanged();
						break;
					case MSG_UPDATE_ANTNUM:
						antNumber.setText((String)msg.obj);
						break;
					default:
						break;
					}
					super.handleMessage(msg);
				}
				
			};
		}
		catch(Exception e)
		{
			
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		btStart.setEnabled(true);
		btStop.setEnabled(false);
	}
	
	private void NotCheckBook()
	{
		try{
			if(Count>1)
			{
				String logStr="";
				String logStart=("第 ")+ (String.valueOf(Count) + "轮,");
				if(mlastIvtClist.size()!=mCurIvtClist.size())
					logStr +=" 标签总数量从" + String.valueOf(mlastIvtClist.size()) 
							+ "到" + String.valueOf(mCurIvtClist.size());
				
				for(int m=0;m<HfData.mlist.size();m++)
				{
					InventoryTagMap map = HfData.mlist.get(m);
					if(map.isCheck)
					{
						String adduid = CheckAddList(map.oldlist,map.newlist);
						String lostuid = CheckLostList(map.oldlist,map.newlist);
						if(adduid.length()>0)
			                logStr += ("\n" + "天线"+map.Antenna+"增加UID：") + adduid;
			            if (lostuid.length() > 0)
			            logStr += ("\n"+"天线"+map.Antenna+"减少UID：") + lostuid;
					}
				}
				if(logStr.length()>0)
				{
					logStr =logStart+logStr;
					 Message msg = mHandler.obtainMessage();
	        		msg.obj = logStr;
	        		msg.what = MSG_UPDATE_INFO;
	        		mHandler.sendMessage(msg);
				}
			}
			mlastIvtClist=new ArrayList<HashMap<String, String>>();
			if(mnewIvtClist.size()>0)
			{
				 for (int i = 0; i < mnewIvtClist.size(); i++) {
			            HashMap<String, String> temp = new HashMap<String, String>();
			            temp = mnewIvtClist.get(i);
			            for(int m=0;m<HfData.mlist.size();m++)
	        			{
	        				InventoryTagMap map = HfData.mlist.get(m);
	        				if(temp.get("tagAnt").equals(String.valueOf(map.Antenna)))
	        				{
	        					map.autolist.add(temp);
	        				}
	        			}
			            mlastIvtClist.add(temp);
			        }
			}
			
			String data = "";
			for(int m=0;m<HfData.mlist.size();m++)
			{
				InventoryTagMap map = HfData.mlist.get(m);
				if(map.isCheck)
				{
					data+=("天线"+map.Antenna+":"+map.newlist.size()+"  ");
					map.oldlist=new ArrayList<HashMap<String, String>>();
					for(int p=0;p<map.newlist.size();p++)
					{
						HashMap<String, String> temp = map.newlist.get(p);
						map.oldlist.add(temp);
					}
					
				}
			}
			Message msg = mHandler.obtainMessage();
			msg.obj = data;
			msg.what = MSG_UPDATE_ANTNUM;
			mHandler.sendMessage(msg);
		}catch(Exception ex)
		{
			Log.d("", ex.toString());
		}
	}
	public  void playSound() {
		 if((soundid==null)||(soundPool==null))return;
		try {
			soundPool.play(soundid, 1, // 左声道音量
					1, // 右声道音量
					1, // 优先级，0为最低
					0, // 循环次数，0无不循环，-1无永远循环
					1 // 回放速度 ，该值在0.5-2.0之间，1为正常速度
			);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void onClick(View arg0) {
		if(arg0==btStart)
		{
			if(mThread==null)
			{
				btStart.setEnabled(false);
				btStop.setEnabled(true);
				btClear.setEnabled(false);
				mWorking=true;
				Count=0;
				mThread = new Thread(new Runnable() 
				{  
		            @Override  
		            public void run() 
		            {  
		            	try{
		            		while(mWorking)
		            		{
		            			long beginTime = System.currentTimeMillis();
		            			boolean selectant=false;
		            			mnewIvtClist=new ArrayList<HashMap<String, String>>();
		            			for(int m=0;m<HfData.mlist.size();m++)
		            			{
		            				InventoryTagMap map = HfData.mlist.get(m);
		            				if(map.isCheck)
		            				{
		            					map.newlist = new ArrayList<HashMap<String, String>>();
		            					map.autolist = new ArrayList<HashMap<String, String>>();
		            					InventoryTagByAnt(map);
		            					selectant = true;
		            				}
		            			}
		            			Count++;
		            			isfinish=false;
		            			if(mnewIvtClist.size()>0)
		            				playSound();
		            			ScanTime = System.currentTimeMillis() - beginTime;
		            			mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
		            			mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
		            			while(!isfinish);
		            			NotCheckBook();
		            			
		            			//doTimeWork();
		            		}
		            		mThread=null;
		            	}catch(Exception ex)
		            	{mThread=null;}
		            }  
		        });
				mThread.start();
			}
		}
		else if(arg0==btStop)
		{
			btStart.setEnabled(true);
			btStop.setEnabled(false);
			btClear.setEnabled(true);
			mWorking =false;
		}
		else if(arg0==btClear)
		{
			Count=0;
			Number=0;
			ScanTime=0;
			txNum.setText("0");
			txTime.setText("0");
			txCount.setText("0");
			antNumber.setText("");
			mCurIvtClist.clear();
			mlastIvtClist.clear();
			mIvtInfolist.clear();
			mnewIvtClist.clear();
			for(int m=0;m<HfData.mlist.size();m++)
			{
				InventoryTagMap map = HfData.mlist.get(m);
				if(map.isCheck)
				{
					map.newlist =new ArrayList<HashMap<String, String>>();
					map.oldlist =new ArrayList<HashMap<String, String>>();
				}
			}
			mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
			mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
			mHandler.removeMessages(MSG_UPDATE_INFO);
			mHandler.sendEmptyMessage(MSG_UPDATE_INFO);
		}
	}
	
	public String CheckLostList(ArrayList<HashMap<String, String>> mList,ArrayList<HashMap<String, String>> nList)
	{
		String result="";
		HashMap<String, String> temp = new HashMap<String, String>();
		if(mList!=null)
		{
			for(int m=0;m<mList.size();m++)
			{
				temp = mList.get(m);
	            String uid = temp.get("tagUid");
				int index = checkIsExist(uid,nList);
		        if (index == -1) {
		        		result+=(uid+" ");
		        } else {
		        	;
		        }
			}
		}
		return result;
	}
	

	public String CheckAddList(ArrayList<HashMap<String, String>> mList,ArrayList<HashMap<String, String>> nList)
	{
		String result="";
		HashMap<String, String> temp = new HashMap<String, String>();
		if(nList!=null)
		{
			for(int m=0;m<nList.size();m++)
			{
				temp = nList.get(m);
	            String uid = temp.get("tagUid");
				int index = checkIsExist(uid,mList);
		        if (index == -1) {
		        	result+=(uid+" ");
		        } else {
		        	;
		        }
			}
		}
		return result;
	}
	
	private void InventoryTagByAnt(InventoryTagMap map)
	{
		try{
			int Antenna = 0;
			switch(map.Antenna)
			{
			case 1:
				Antenna=1;
				break;
			case 2:
				Antenna=2;
				break;
			case 3:
				Antenna=4;
				break;
			case 4:
				Antenna=8;
				break;
			}
			int fCmdRet = HfData.reader.SetAntenna((byte)Antenna);
			SystemClock.sleep(10);
			byte state = (byte)0x06;
			do{
				byte[]UID= new byte[25600];
				int[]CardNum = new int[1];
				CardNum[0]=0;
				fCmdRet = HfData.reader.Inventory(state, UID, CardNum);
				if(CardNum[0]>0)
				{
					for(int m=0;m<CardNum[0];m++)
					{
						byte[]daw = new byte[9];
						System.arraycopy(UID, m*9, daw, 0, 9);
						String uidStr = HfData.bytesToHexString(daw, 1, 8);
						HashMap<String, String> temp = new HashMap<String, String>();
						//"tagUid","tagAnt","tagRssi"
						temp.put("tagUid", uidStr);
						temp.put("tagAnt", String.valueOf(map.Antenna));
						int index = checkIsExist(uidStr,mnewIvtClist);//总统计表
						if(index==-1)//不存在
						{
							mnewIvtClist.add(temp);
						}
						index = checkIsExist(uidStr,map.newlist);//单个天线表
						if(index==-1)//不存在
						{
							map.newlist.add(temp);
						}
					}
				}
				else
				{
					Log.d("Read", "notag");
				}
				state = (byte)0x82;
				if((fCmdRet==0x30)&&(!mWorking))
				{
					break;
				}
			}while(fCmdRet!=0x0E);
		}catch(Exception ex)
		{
			Log.d("", ex.toString());
		}
	}
	
	public boolean isEmpty(String strEPC)
	{
		return strEPC==null || strEPC.length()==0;
	}
	public int checkIsExist(String strUID,ArrayList<HashMap<String, String>> mList){
        int existFlag = -1;
        if (isEmpty(strUID)) {
            return existFlag;
        }
        if(mList==null)
        {
        	return existFlag;
        }
        String tempStr = "";
        for (int i = 0; i < mList.size(); i++) {
            HashMap<String, String> temp = new HashMap<String, String>();
            temp = mList.get(i);
            tempStr = temp.get("tagUid");
            if (strUID.equals(tempStr)) {
                existFlag = i;
                break;
            }
        }
        return existFlag;
    }
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub

	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mWorking =false;
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	

}
